<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 购物车
 * @author www.dingwei.cn
 */
class Cart extends MY_Controller {
	
	/**
	 * 支付模型
	 * @var ConsumerCartModel
	 */
	public $mCart;
	
	/**
	 * 产品模型
	 * @var ConsumerProductModel
	 */
	public $mProduct;
	
	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerCartModel', 'mCart', 'consumer');
		$this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
	}
	
	/**
	 * 加入购物车
	 */
	public function add(){
		//表单验证
		$vConf = array(
            array('product_id', '产品id', 'required|is_natural_no_zero'),
            array('sort', '规格id', 'is_numeric'),
            array('quantity', '数量', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);

		$productId = post('product_id');
		$sort = post('sort');
		$quantity = post('quantity');
		$tags = post('tags');
		$type = (int)post('type');
        //获取产品
        $tA = $this->mProduct->getInfo($productId, 0, true);
        if ( ! $tA){
            $this->appReturn(0, '产品不存在');
        }
		$hasVariant = $this->mProduct->hasVariant($productId);
		if($hasVariant && !$sort){
			$this->appReturn(0, '参数错误1');
		}elseif( ! $hasVariant){
			$sort = 0;
		}
        $dbQuantity = $this->mCart->getQuantity($this->userId, $productId, $sort);
        if ($type == 2){
            $quantity += $dbQuantity;
        }

		$data = [['product_id' => $productId, 'sort' => $sort, 'quantity' => $quantity, 'tags' => $tags]];

		$data = $this->mProduct->canAddOrder($this->userId, $data, true);
		if($data === false){
			$this->appReturn(0, '参数错误2');
		}elseif( ! is_array($data)){
            if(!(strpos($data,'下架') === false)){
                $exData = explode('-', $data);
                $this->appReturn(0, $exData[0].'，请重新选购',(object)array());
            }else{
                $this->appReturn(0, $data);
            }


		}

        if( ! $quantity){
			$total = $this->mCart->getProductCount($this->userId);
			$max = $this->mCart->maxCartProductCount();
			if($total >= $max){
				$this->appReturn(0, '你的购物车已满');
			}
		}
		
		$data = [
				  'consumer_id' => $this->userId,
				  'product_id' => $productId,
				  'variant_id' => $sort,
				  'quantity' => $quantity,
				  'tags' => $tags,
				  'addtime' => time()
		];


		if($dbQuantity){
			$this->db->where(['consumer_id' => $this->userId, 'product_id' => $productId]);
			if($hasVariant){
				$this->db->where('variant_id', $sort);
			}
			
			if( ! $this->mCart->update($this->mCart->tbShoppingCart, $data)){
				$this->appReturn(0, '加入购物车失败');
			}
		}else{
			if( ! $this->mCart->insert($this->mCart->tbShoppingCart, $data)){
				$this->appReturn(0, '加入购物车失败');
			}
		}
        $tData =  $this->getMerchantCart($tA['merchant_id']);
		$this->appReturn(1, '', $tData);
	}

	/**
	 * 编辑购物车
	 */
	public function edit(){
		
		//表单验证
		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
// 				array('sort', '规格id', 'is_natural_no_zero'),
				array('quantity', '数量', 'required|is_natural_no_zero'),
				array('change_sort', '规格id', 'is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$productId = post('product_id');
		$updateSort = $sort = post('sort');
        $tags = post('tags');
		$quantity = post('quantity');
		$changeSort = post('change_sort');
		
		if ( ! $quantity && ! $sort && ! $changeSort){
			$this->appReturn(0,'参数错误');
		}

        //获取产品
        $tA = $this->mProduct->getInfo($productId, 0, true);
        if ( ! $tA){
            $this->appReturn(0, '产品不存在');
        }

		/**
		 * 判断之前有没规格
		 * @var Ambiguous $hasVariant
		 */
		$hasVariant = $this->mProduct->hasVariant($productId);
		if($hasVariant && ! $sort){
			$this->appReturn(0, '参数错误1');
		}elseif( ! $hasVariant){
			$sort = 0;
		}
		
		$dbQuantity = $this->mCart->getQuantity($this->userId, $productId, $sort);
		if( ! $dbQuantity){
			$this->appReturn(0, '购物车中不存在该商品');
		}
		
		//验证变更的规格在购物车中是否存在
		if($changeSort){
			$tI = $this->mCart->getQuantity($this->userId, $productId, $changeSort);
			if($tI){
				$this->appReturn(0, '不能变更规格，已经在购物车中存在');
			}
			
			if( ! $this->mProduct->hasVariant($productId, $changeSort)){
				$this->appReturn(0, '规格更改失败，规格不存在');
			}
			
			$sort = $changeSort; 
		}

		$data = [['product_id' => $productId, 'sort' => $sort, 'quantity' => $quantity]];
		$data = $this->mProduct->canAddOrder($this->userId, $data, true, true);
		if($data === false){
			$this->appReturn(0, '参数错误2');
		}elseif( ! is_array($data)){

            if(!(strpos($data,'下架') === false)){
                $exData = explode('-', $data);
                $this->appReturn(-1, $exData[0].'，请重新选购',(object)array());
            }else{
                $this->appReturn(0, $data,(object)array());
            }
		}
		
		if( ! $dbQuantity){
			$total = $this->mCart->getProductCount($this->userId);
			$max = $this->mCart->maxCartProductCount();
			if($total >= $max){
				$this->appReturn(0, '你的购物车已满');
			}
		}
		//$this->appReturn(0,$sort);
		$tData = [
				  'quantity' => $quantity,
				  'variant_id' => $sort
			];
		
		$this->db->where(['consumer_id' => $this->userId, 'product_id' => $productId]);
		if($hasVariant){
			$this->db->where('variant_id', $updateSort);
		}
		
		if( ! $this->mCart->update($this->mCart->tbShoppingCart, $tData)){
			$this->appReturn(0, '编辑失败');
		}
		
		$edit = array(
				'sort'			=> $updateSort,//当前sort
				'change_sort'	=> empty($changeSort)?$sort:$changeSort,//更改后的sort 不存在 就用旧的sort html要更新
				'quantity'  	=> $quantity, //变更购买的数量
				'property' 		=> isset($data[0]['property'])?implode('/',json_decode($data[0]['property'],true)):'',//变更购买的组合
				'price' 		=> isset($data[0]['v_price'])?$data[0]['v_price']:$data[0]['goods_price'],//变更后组合的单价
		);
        $tData =  $this->getMerchantCart($tA['merchant_id']);
		$this->appReturn(1, '', $tData);
	}

    /**
     * 商家购物车
     * @param $merchantId
     * @return array
     */
    public function getMerchantCart($merchantId){
        $this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
        $this->loadModel('ConsumerCartModel', 'mCart','consumer');
        /**
         * 商家信息
         * @var array $tShop
         */

        $tData = $this->mMerchant->getShopInfo($merchantId,true);
        if (! $tData){
            $this->appReturn(0,'商家不存在');
        }

        $tData = array();
        $lunch_box_fee = 0; //打包费
        $total = 0; // 总金额
        $productAmount = 0;//商品总额
        $number = 0; // 总数量

        if ($this->userId){
            $tCart = $this->mCart->getList($this->userId,$merchantId);

            if (isset($tCart[$merchantId])){
                foreach ($tCart[$merchantId] as $k=>$v){
                    $v['property'] = array_values($v['property']);
                    $v['property_str'] = implode('/', $v['property']);
                    $lunch_box_fee += $v['lunch_box_fee'];
                    $productAmount += $v['price'] * $v['quantity'];
                    $number += $v['quantity'];
                    $tData[] = $v;
                }
            }
        }

        return array(
            'total' => $productAmount+$lunch_box_fee,
            'lunch_box_fee'=>$lunch_box_fee,
            'number' => $number,
            'list'=>$tData
        );
    }

	/**
	 * 列出产品
	 */
	public function shop_car(){
		if ($this->isDEBUG){
			$this->userId = 2;
		}
		$tA = $this->mCart->getList($this->userId);
		$this->loadModel('MerchantUserModel', 'mMuser', 'merchant');
		$data = [];

		$JsData = array();
		$merData = array();
		if($tA){
			//判断该商品是否有规格可以选择
			$tProductIds = array();
			foreach ($tA as $k=>$v){
				foreach ($v as $kk => $vv){
					if ( ! in_array($vv['id'], $tProductIds)){
						$tProductIds[] = $vv['id'];
					}
				}
			}
			
			//判断产品是否有组合规格
			$tProperty = $this->mProduct->getPropertyListByIds($tProductIds);
			
			$merchant = $this->mMuser->getInfoByIds(array_keys($tA));
			
			foreach ($tA as $k => $v){
				foreach ($v as $kk => $vv){
					if (empty($vv['sort'])){
						$v[$kk]['sort'] = "0";
					}
					$v[$kk]['property'] = implode('/', $vv['property']);
					$v[$kk]['is_variant'] = isset($tProperty[$vv['id']])?"1":"0";//是否有规格可以选择， 1-是  0-否
				}
				
				$data[] = [
							'merchant_id'=>$k,
						    'name' => isset($merchant[$k]) ? $merchant[$k]['shop_name'] : '',
							'min_consume'=>isset($merchant[$k])? $merchant[$k]['min_consume'] : '',
							'products' => $v
				];
				
				//组装js数据
				foreach ($v as $kk=>$vv){
					if (empty($vv['sort'])){
						$vv['sort'] = "0";
						$JsData[$vv['id']][] = $vv;
					}else{
						$JsData[$vv['id']][$vv['sort']] = $vv;
					}
				}
				
				//组装商家信息
				
				if ( ! array_key_exists($k, $merData)){
					$vDate = array(
							'min_consume'=>isset($merchant[$k])? $merchant[$k]['min_consume'] : '',
					);
					$merData[$k] = $vDate;
				}
			}
		}
		
				//print_r($merData);
		
		$data = $this->view('cart/list', ['data' => $data,'jsData'=>$JsData,'merData'=>$merData], '', '', '', true);
		if ($this->isDEBUG){
			echo $data;
			exit();
		}
		$this->appReturn(1, '', $data);
	}
	
	/**
	 * 删除购物车商品
	 */
	public function delete(){
		
		//表单验证
		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
// 				array('sort', '规格id', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$productId = post('product_id');
		$sort = post('sort');
        //获取产品
        $tA = $this->mProduct->getInfo($productId, 0, true);
        if ( ! $tA){
            $this->appReturn(0, '产品不存在');
        }

		$hasVariant = $this->mProduct->hasVariant($productId);
		if($hasVariant && ! $sort){
			$this->ajaxReturn(0, '参数错误');
		}elseif( ! $hasVariant){
			$sort = 0;
		}
		
		$this->db->where([
				          'consumer_id' => $this->userId,
						  'product_id' => $productId
		]);
		if($hasVariant){
			$this->db->where('variant_id', $sort);
		}
		
		if($this->mCart->delete($this->mCart->tbShoppingCart)){
            $tData =  $this->getMerchantCart($tA['merchant_id']);
			$this->appReturn(1, '已删除', $tData);
		}

		$this->appReturn(0, '删除失败');
	}
	
	/**
	 * 清空购物车
	 */
	public function deleteAll(){

		if ( ! $this->mCart->getList($this->userId)){
			$this->appReturn(0,'购物车为空'.$this->userId);
		}
		
		$this->db->where('consumer_id', $this->userId);
		if($this->mCart->delete($this->mCart->tbShoppingCart)){
			$this->appReturn(1, '已清空');
		}
		
		$this->appReturn(0, '清空失败');
	}
	
	/**
	 * 规格
	 */
	public function specification(){
		
		echo $this->view('cart/specification', null, '', '', '', true);
	}
}